const schedule = require("node-schedule");
const PublicIp = require("nodejs-publicip");
const sendMail = require("../utils/mail");

const encodeIP = (ip) => {
  let str = ip.replace(/\./g, "-");
  let before = Math.floor(Math.random() * 100);
  let after = Math.floor(Math.random() * 100);
  return `SH-${before}-${str}-${after}`;
};

let oldIPInfo = {
  ip: "",
  time: "",
};
const getPublicIP = async () => {
  console.log(`开始执行 任意门 任务`);
  try {
    let ip = await new PublicIp().queryPublicIPv4Address(); //IPv4 地址
    let encodedIP = encodeIP(ip);
    if (oldIPInfo.ip !== ip) {
      let msg = `应答：${encodedIP}，上次更新于：${oldIPInfo.time || "/"}`;
      try {
        sendMail({
          subject: `NAS -【任意门】执行完毕`,
          content: msg,
        });
      } catch (err) {
        console.log(err);
      }

      // 更新本地IP信息
      oldIPInfo.ip = ip;
      oldIPInfo.time = new Date();

      console.log(`new ip: ${JSON.stringify(oldIPInfo, "\t", 2)}`);
    } else {
      console.log(`same ip：${encodedIP}`);
    }

    return encodedIP;
  } catch (err) {
    return "";
  }
};

module.exports = {
  name: "任意门",
  run: getPublicIP,
  config: {
    // hour: 16,
    // minute: 22,
    // second: 40,

    minute: new schedule.Range(0, 59, 10), // 每10分钟执行一次
  },
};
